<?php

namespace addons\weixin\controller;

use app\common\library\Auth;
use think\Config;
use addons\weixin\library\WechatService;
use app\admin\model\weixin\User as WechatUser;
use app\admin\model\User;
use think\Hook;
use think\Cookie;
use think\Session;

/**
 * 微信公众号接口
 */
class Index extends \think\addons\Controller
{

    public $auth = null;
    public $wxid = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->auth = $auth = Auth::instance();
    }

    public function test2(){
        $toUserName = "oZgEx1HJV9s7kXY2GQ8cpWHTxyM43";
        $info =  \app\admin\model\User::where(["openid"=>$toUserName])->find();
        if(!$info){
            echo 1;die;
        }

        print_r($info);die;

    }

    /**
     * 微信公众号授权登录和jssdk分享演示
     * http://你的域名/addons/weixin
     * http://wxad.lvfree.net/addons/weixin
     */
    public function index()
    {
        //获取url参数
        $url =  $_SERVER["REQUEST_URI"];
        $wxid = $this->getQuerystr($url,"wxid");

        if($wxid){
            $this->wxid = $wxid;
            Session::set('wxid',$wxid);
            $wxtoken = Session::get('wxtoken');
            if($wxtoken){
                Session::set('wxtoken', null);
                Session::set('wxid', null);
            }else{
                $this->login($wxid);
            }

        }


        $openid = Session::get('openid');
        if($openid){
            $info = \app\admin\model\User::where(["openid"=>$openid])->find()->toArray();
            if($info){
                $this->assign("uid",$info["id"]);
                $this->assign("username",$info["nickname"]);
                $this->assign("avater",$info["avatar"]);
            }

        }


        return $this->fetch();
    }

    /**
     * 微信公众号服务  需要在公众号配置的时候带上
     * http://你的域名/addons/weixin/index/serve
     */
    public function serve()
    {

        //$test  ='<xml><ToUserName><![CDATA[oomj21UsyT3B3G2vFrf2VvVoy71Q]]></ToUserName><FromUserName><![CDATA[gh_3fc1638fc288]]></FromUserName><CreateTime>1602915341</CreateTime>
        //<MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item id="0"><Title><![CDATA[请完善信息1]]></Title><Description><![CDATA[请完善您的信息，方便相互联系，我是你的客服]]></Description>
        //<Url><![CDATA[http://wxad.lvfree.net]]></Url><PicUrl><![CDATA[http://local.wxad.com//uploads/20201016/e85be18b334cc277ca76737288ec907b.png]]></PicUrl></item></Articles></xml>';

        $wxid = $this->request->get("wxid"); //获取微信公众号获取token 时 对应URL配置的wxid


        return WechatService::serve($wxid);
    }

    /**
     * 公众号权限配置信息获取
     * http://你的域名/addons/weixin/index/config
     */
    public function config()
    {
        $wxModel = new \app\admin\model\weixin\Config();
        $wxid =  Session::get('wxid');

        $wxConfigData = $wxModel->where([
            'group' => 'weixin', 'wx_id' => $wxid
        ])->select();

        $wxConfig = [];
        foreach ($wxConfigData as $val) {
            $wxConfig[$val['name']] = $val['value'];
        }
        $url = $this->request->post('url');
        $jsSdk = json_decode(WechatService::jsSdk(urldecode($url)), true);
        return json(['code' => 1, 'data' => array_merge($wxConfig, $jsSdk)]);
    }

    /*
     * 微信公众号发起授权
     * http://你的域名/addons/weixin/index/login
     * */
    public function login($wxid)
    {

        $wechat_data = \app\admin\model\weixin\Config::where(['group' => 'weixin','wx_id'=>$wxid])->select();

        foreach ($wechat_data as $k => $v) {
            $value = $v->toArray();
            if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                $value['value'] = explode(',', $value['value']);
            }
            if ($value['type'] == 'array') {
                $value['value'] = (array)json_decode($value['value'], true);
            }
            $wechat[$value['name']] = $value['value'];
        }


        $return_url = "http://" . $_SERVER['SERVER_NAME'] . "/addons/weixin/index/auth";
        $redirect_uri = urlencode($return_url);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$wechat['appid']}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";


        header('location:' . $url);
        exit();
    }


    /*
 * 微信公众号发起授权
 * http://你的域名/addons/weixin/index/login
 * */
    public function loginold()
    {
        $wxid = Session::get('wxid');
        $wechat_data = \app\admin\model\weixin\Config::where(['group' => 'weixin','wx_id'=>$wxid])->select();

        foreach ($wechat_data as $k => $v) {
            $value = $v->toArray();
            if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                $value['value'] = explode(',', $value['value']);
            }
            if ($value['type'] == 'array') {
                $value['value'] = (array)json_decode($value['value'], true);
            }
            $wechat[$value['name']] = $value['value'];
        }


        $return_url = "http://" . $_SERVER['SERVER_NAME'] . "/addons/weixin/index/auth";
        $redirect_uri = urlencode($return_url);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$wechat['appid']}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";



        header('location:' . $url);
        exit();
    }



    /**
     * 公众号授权回调登陆
     * http://你的域名/addons/weixin/index/auth
     */
    public function auth()
    {

        $spreadId = intval($this->request->param('spread'));
        $login_type = $this->request->param('login_type', '');
        try {

            $wechatInfo = WechatService::oauthService()->user()->getOriginal();
        } catch (\Exception $e) {

            $this->error('授权失败', '', ['message' => $e->getMessage(), 'line' => $e->getLine()]);
        }
        $info = [];
        file_put_contents("wechatinfo.json",var_export($wechatInfo,true));
        if (!isset($wechatInfo['nickname'])) {
            $wechatInfo = WechatService::getUserInfo($wechatInfo['openid']);



            //没有关注公众号也没有会的微信用户昵称
            if (!$wechatInfo['subscribe'] && !isset($wechatInfo['nickname'])) {
                exit(WechatService::oauthService()->scopes(['snsapi_userinfo'])
                    ->redirect($this->request->url(true))->send());
            }
            //得到标签列表
            if (isset($wechatInfo['tagid_list'])) {
                $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
            }
        } else {

            //判断是否已经存储过用户 ，如果没有则新增
            $resdata = $this->getUserInfo($wechatInfo);

        }

        //授权成功后
        //$uid = WechatUser::onWechatOauthAfter($wechatInfo, $spreadId, $login_type);

        //登录
        $ret = $this->auth->direct($resdata["id"]);
        if ($ret) {
            Session::set('wxtoken', $this->auth->getToken());
            Session::set('openid',$resdata["openid"]);
            $this->redirect("addons/weixin/index");
        } else {
            $this->error($this->auth->getError());
        }
    }

    //新增用户或者返回用户信息
    public function getUserInfo($wechatinfo){
        $where["openid"]  = $wechatinfo["openid"];
        $info = \app\admin\model\User::where($where)->find();

        if($info){
            $data["nickname"] = $wechatinfo["nickname"];
            $data["gender"] = $wechatinfo["sex"];
            $data["city"] = $wechatinfo["city"];
            $data["province"] = $wechatinfo["province"];
            $data["country"] = $wechatinfo["country"];
            $data["avatar"] = $wechatinfo["headimgurl"];
            $data["updatetime"] =time();
            \app\admin\model\User::where($where)->update($data);

            $resdata["openid"] =  $wechatinfo["openid"];
            $resdata["id"] =  $info["id"];

            return $resdata;
        }else{
            $data["openid"] = $wechatinfo["openid"];
            $data["nickname"] = $wechatinfo["nickname"];
            $data["gender"] = $wechatinfo["sex"];
            $data["city"] = $wechatinfo["city"];
            $data["province"] = $wechatinfo["province"];
            $data["country"] = $wechatinfo["country"];
            $data["avatar"] = $wechatinfo["headimgurl"];
            $insid = \app\admin\model\User::where($where)->insertGetId($data);

            $resdata["openid"] =  $wechatinfo["openid"];
            $resdata["id"] =  $insid;

            return $resdata;

        }


    }


    //完善信息
    public function updataInfo(){

        $param = $this->request->post();

        $code = $param["usercode"];

        if(empty($code)){
            return 9;//验证码不能为空
            exit;
        }

        //验证码 检测 这里就不考虑 验证码使用过的情况 只比较最后一个验证码
        $smsinfo = \app\admin\model\Smslog::where("sms_type=0 and sms_tel={$param["userphone"]}")->order("id desc")->field("sms_code")->find();
        if($code != $smsinfo["sms_code"]){
            return 8;
            exit;
        }

        $id = $param["uid"];
        $data["mobile"] = $param["userphone"];
        $data["nickname"] = $param["username"];
        $data["updatetime"] = time();

        $eff = \app\admin\model\User::where("id={$id}")->update($data);
        if($eff){
            return 1;
            exit;
        }else{
            return 2;
            exit;
        }

    }


    //发送短信
    public function sendCode(){
        $param = $this->request->post();
        $account = $param["userphone"];
        $type = 0;//预留
        $res = sendsms($account,$type);
        return $res;
    }

    //发送短信 赛邮-云通信
    public function sySendCode(){
        $param = $this->request->post();
        $account = $param["userphone"];
        $res = sysendsms($account);
        return $res;
    }


    public function test(){

        $wxid = \think\Cookie::get('wxid');

        print_r($wxid);die;

        die;

        $url =  $_SERVER["REQUEST_URI"];
        $res = $this->getQuerystr($url,"wxid");

        dump($res);

        die;

        $phone = "13151599495";
        $type = 0;
        $res = sendsms($phone,$type);

        print_r($res);die;

    }

    /*
     * 函数说明：获取URL某个参数的值
     *
     * @access  public
     * @param   $url  路径
     * @param   $key  要获取的参数
     * @return  string     返回参数值
     */
    function getQuerystr($url,$key){
        $res = '';
        $a = strpos($url,'?');
        if($a!==false){
            $str = substr($url,$a+1);
            $arr = explode('&',$str);
            foreach($arr as $k=>$v){
                $tmp = explode('=',$v);
                if(!empty($tmp[0]) && !empty($tmp[1])){
                    $barr[$tmp[0]] = $tmp[1];
                }
            }
        }
        if(!empty($barr[$key])){
            $res = $barr[$key];
        }
        return $res;
    }

}
